import axios from 'axios';
import { ElMessage, ElLoading } from 'element-plus';


const service = axios.create({
    baseURL: 'http://localhost:3000',
    timeout: 5000
})
let loadingInstance:any;

service.defaults.headers['content-type'] = 'application/json'

service.interceptors.request.use(config => {
    loadingInstance = ElLoading.service({
        fullscreen: true,
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
    });
    return config;
}, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
});

// 添加响应拦截器
service.interceptors.response.use(response => {
    loadingInstance && loadingInstance.close();
    // 对响应数据做点什么
    let code = response.status;
    switch (code) {
        case 502:
            ElMessage({ message: response.data.message, type: 'warning' })
            break;
        case 401:
            ElMessage({ message: response.data.message, type: 'error' })
            break;
        case 500:
            ElMessage({ message: '服务器打瞌睡了！', type: 'error' })
            break;
        case 400:
            ElMessage({ message: '参数错误！', type: 'error' })
            break;
        case 405:
            ElMessage({ message: '请检查你的请求类型！', type: 'error' })
            break;
        case 200:
            if (response.data) {
                return response.data
            } else {
                return response
            }
        default:
            return response;
    }
},
    error => {
        // 对响应错误做点什么
        return Promise.reject(error);
    });

export default service